<?php

namespace App\Services\FinishGroup;

use Carbon\Carbon;
use App\Models\Group;
use App\Models\Broadcast;
use App\Models\SeckillProduct;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class FinishGroup
{
	protected $group;
	
	public function __construct(Group $group)
	{
		$this->group = $group;
	}
	
	protected function finish()
	{
		DB::transaction(function () {
			
			$this->group->update(['is_finished' => 1]);

			$count = $this->group->records()->count();
			$price = $this->group->product->price_lowest;
			$groupNumber = $this->group->product->group_number;

			$rateArr = config("site.joins.{$groupNumber}");

			
			$rate = $rateArr[$count-1];
			
			$price = $price * $rate / 100;



			/*if($count == 1){
				$price = $price * cs('sale')->one_person_group_rewards / 100  *  $this->group->product->reward_rate / 100;
				
			}elseif($count ==2){
				$price = $price * cs('sale')->two_person_group_rewards / 100 *  $this->group->product->reward_rate / 100;

			}else{

				$price = $price * cs('sale')->more_person_group_rewards / 100 *  $this->group->product->reward_rate / 100;
			}*/

			Broadcast::create([
				'message'=>"开团成功，获得{$price}元现金返现",
				'user_id'=>$this->group->user_id,
			]);

			foreach($this->group->records as $v){
				Broadcast::create([
					'message'=>"参团成功获得开团卡，享返现特权",
					'user_id'=>$v->user_id,
				]);


			}



			account_balances($this->group->user)->plusGroupBalances($price);
		});
	}
	
	protected function canBeClosed()
	{
		if ($this->group->isFinished()) return false;
		if ($this->group->records()->count() < 1) return false;
		return true;
	}
	
	
	public function finishByJob()
	{
		if (! $this->canBeClosed()) return;
		
		$this->finish();
	}
}
